//
//  OperationBillGuiJiVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2020/11/19.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "OperationBillGuiJiVC.h"
#import "GuiJiStatusModel.h"
#import "GuiJiStatusModel.h"
#import "GuiJiStatusCell.h"
#import <MapKit/MapKit.h>
#import "WayBillMapLocationModel.h"
#import "WayBillPolyline.h"
#import "LJAnnotation.h"
#import "GuiJiAnnotationView.h"

@interface OperationBillGuiJiVC () <MKMapViewDelegate,UITableViewDelegate,UITableViewDataSource> {
    CGFloat tableViewTopMin;
    CGFloat tableViewTopMid;
    CGFloat tableViewTopMax;
}

@property (nonatomic, strong) NSArray <GuiJiStatusModel *>*statusArray;
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <NSArray *>*locationMut;

@end

@implementation OperationBillGuiJiVC

-(NSMutableArray<NSArray *> *)locationMut {
    if (!_locationMut) {
        _locationMut = [NSMutableArray array];
    }
    return _locationMut;
}

-(NSArray<GuiJiStatusModel *> *)statusArray {
    if (!_statusArray) {
        _statusArray = [NSArray array];
    }
    return _statusArray;
}

-(UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, StatusBarHeight + 7, 44, 44)];
        [_backBtn setImage:[UIImage imageNamed:@"icon_map_back"] forState:0];
        [_backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

- (void)backClick {
    [self.rt_navigationController popViewControllerAnimated:YES];
}

-(MKMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
        _mapView.delegate = self;
    }
    return _mapView;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, tableViewTopMax, ScreenW - 30, ScreenH - tableViewTopMin - BottomHeight)];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"img_occupy"
             titleStr:@""
            detailStr:@""];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    tableViewTopMin = 150;
    tableViewTopMax = ScreenH - 150;
    tableViewTopMid = (tableViewTopMax - tableViewTopMin) * 0.5 + tableViewTopMin;
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.backBtn];
    [self requestForData];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (self.tableView.nim_top >= tableViewTopMid) {
        __weak_self;
        [UIView animateWithDuration:0.5 animations:^{
            __strong_self;
            weakself.tableView.nim_top = strongSelf->tableViewTopMax;
        } completion:nil];
    }else {
        __weak_self;
        [UIView animateWithDuration:0.5 animations:^{
            __strong_self;
            weakself.tableView.nim_top = strongSelf->tableViewTopMin;
        } completion:nil];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        CGFloat offSetY = scrollView.contentOffset.y;
        if (self.tableView.nim_top < tableViewTopMin) {
            self.tableView.nim_top = tableViewTopMin;
        }else if (self.tableView.nim_top > tableViewTopMax) {
            self.tableView.nim_top = tableViewTopMax;
        }else {
            self.tableView.nim_top -= offSetY;
        }
    }
}

- (void)requestForData {
    [HttpRequest PostWithApi:LogisticsSupplierOperationBillGuiJi params:@{@"o_id":@(self.o_id)} progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.statusArray = [GuiJiStatusModel mj_objectArrayWithKeyValuesArray:responseObject[@"status_list"]];
            self.statusArray.firstObject.isFirst = YES;
            self.statusArray.lastObject.isLast = YES;
            [self.tableView reloadData];
            
            NSArray *arr = (NSArray *)[responseObject objectForKey:@"track"];
            NSMutableArray *mm = [NSMutableArray array];
            [arr enumerateObjectsUsingBlock:^(id  _Nonnull a_obj, NSUInteger a_idx, BOOL * _Nonnull a_stop) {
                NSMutableArray *mut = [NSMutableArray array];
                [((NSArray *)a_obj) enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [mut addObject:[WayBillMapLocationModel mj_objectWithKeyValues:obj]];
                }];
                [mm addObject:mut];
            }];
//            NSMutableArray *mut = [NSMutableArray array];
//            WayBillMapLocationModel *mo1 = [WayBillMapLocationModel new];
//            mo1.lat = @"31.3";
//            mo1.lng = @"120.59";
//            [mut addObject:mo1];
//            WayBillMapLocationModel *mo2 = [WayBillMapLocationModel new];
//            mo2.lat = @"31.65";
//            mo2.lng = @"120.75";
//            [mut addObject:mo2];
//            [mm addObject:mut];
//
//            NSMutableArray *mut2 = [NSMutableArray array];
//            WayBillMapLocationModel *mo3 = [WayBillMapLocationModel new];
//            mo3.lat = @"31.7";
//            mo3.lng = @"119.33";
//            [mut2 addObject:mo3];
//            WayBillMapLocationModel *mo4 = [WayBillMapLocationModel new];
//            mo4.lat = @"31.2";
//            mo4.lng = @"118.35";
//            [mut2 addObject:mo4];
//            [mm addObject:mut2];
            self.locationMut = mm;
            [self configMapLine];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)configMapLine {
    if (self.locationMut.count) {
        NSMutableArray *quYuArray = [NSMutableArray array];
        [self.locationMut enumerateObjectsUsingBlock:^(NSArray * _Nonnull a_obj, NSUInteger a_idx, BOOL * _Nonnull a_stop) {
            CLLocationCoordinate2D arr[a_obj.count];
            for (int i = 0; i < a_obj.count; i ++) {
                WayBillMapLocationModel *model = a_obj[i];
                arr[i] = CLLocationCoordinate2DMake([model.lat doubleValue], [model.lng doubleValue]);
                if (i == 0) {
                    LJAnnotation *tiAn = [LJAnnotation new];
                    tiAn.coordinate = CLLocationCoordinate2DMake([model.lat doubleValue], [model.lng doubleValue]);
                    [self.mapView addAnnotation:tiAn];
                    [quYuArray addObject:tiAn];
                }
            }
            WayBillPolyline *cc = (WayBillPolyline *)[WayBillPolyline polylineWithCoordinates:arr count:a_obj.count];
            if (a_idx == 0) {
                cc.color = HexColor(0x6DD26D);
            }else if (a_idx == 1) {
                cc.color = HexColor(0xDEA543);
            }else if (a_idx == 2) {
                cc.color = HexColor(0xF68163);
            }else if (a_idx == 3) {
                cc.color = HexColor(0x6386F6);
            }else if (a_idx == 4) {
                cc.color = HexColor(0x5CE88F);
            }else if (a_idx == 5) {
                cc.color = HexColor(0xE8B55C);
            }else if (a_idx == 6) {
                cc.color = HexColor(0x427AE9);
            }else if (a_idx == 7) {
                cc.color = HexColor(0xF55555);
            }else if (a_idx == 8) {
                cc.color = HexColor(0x63ACF6);
            }else {
                cc.color = [UIColor blackColor];
            }
            [self.mapView addOverlay:cc];
        }];
        if (!quYuArray.count) {
            [self.mapView removeAnnotations:[self.mapView annotations]];
        }else {
            self.mapView.region = [LJAnnotation regionForAnnotations:quYuArray];
        }
    }
}

-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    if ([overlay isKindOfClass:[WayBillPolyline class]]) {
        //如果有MKPloylineView的overlay,将其画出
        MKPolylineRenderer *lineView = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
        lineView.strokeColor = ((WayBillPolyline *)overlay).color;
        lineView.lineWidth = 3;
        return lineView;
    }
    return nil;
}

- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    // 自定义大头针
    if ([annotation isKindOfClass:[LJAnnotation class]]) {
        static NSString *pinID = @"GuiJiAnnotationView";
        GuiJiAnnotationView *customPinView = (GuiJiAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
        if (!customPinView) {
           customPinView = [[GuiJiAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID];
        }
        customPinView.annotation = (LJAnnotation *)annotation;
        return customPinView;
    }
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.statusArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GuiJiStatusCell *cell = [GuiJiStatusCell GuiJiStatusCellWithTableView:tableView];
    cell.model = self.statusArray[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GuiJiStatusCell *cell = [GuiJiStatusCell GuiJiStatusCellWithTableView:tableView];
    cell.model = self.statusArray[indexPath.row];
    return cell.height;
}

@end
